package cn.swunet.dao;

import java.util.List;

import cn.swunet.bean.User;

public class UserDao extends BaseDao<User>{
	public List<User> getAll(){
		return this.getList("SELECT * FROM user");
	}
	
	public User getUserById(int id) {
		String sql = "SELECT * FROM user WHERE id = ?";
		return this.getOne(sql, id);
	}	
	
	public String getUserPasswd(int id) {
		String sql = "SELECT * FROM user WHERE id = ?";
		return this.getOne(sql, id).getPasswd();
	}
	
	public int setUserHostById(int id, String IpAddr, int port) {
		String sql = "UPDATE user SET activeIp = ?, activePort = ?  WHERE id = ?";
		return update(sql, IpAddr, port, id);
	}
	
	public int clearUserHostById(int id) {
		String sql = "UPDATE user SET activeIp = null, activePort = null  WHERE id = ?";
		return update(sql, id);
	}
	
	public User getUserByName(String uname) {
		String sql = "SELECT * FROM user WHERE username = ?";
		return this.getOne(sql, uname);
	}
	
	public List<User> getFriends(int id){
		String sql = "SELECT * FROM user WHERE id IN (SELECT  friend_id FROM friend WHERE u_id = ?)";
		return this.getList(sql, id);
	}
	
	public int addUser(User user) {
		String sql = "INSERT INTO user (username, passwd) VALUES (?, ?)";
		return this.update(sql, user.getUsername(), user.getPasswd());
	}
	
	public int addFriend(int user_id, int friend_id) {
		String sql = "INSERT INTO friend (u_id, friend_id) VALUES (?, ?);"
					+ "INSERT INTO friend (u_id, friend_id) VALUES (?, ?);";
		return this.update(sql, user_id, friend_id, friend_id, user_id);
	}
}
